package com.bing.beans;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by kaibb on 14-7-26.
 */
public class DBJndi {
    private Connection connection;
    private DataSource ds;
    private PreparedStatement pStatement;
    private ResultSet resultSet;
    private String sql;

    public DBJndi() throws NamingException, SQLException {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
        connection = ds.getConnection();
    }

    public ResultSet getAllEmployeeByName(String name) throws SQLException {

        //bingsay 这里like 必须要用?号..% %在设置值的时候加上去.否则会报错
        sql = "select * from employees where first_name like ? order by employee_id ";
        pStatement = connection.prepareStatement(sql);
        System.out.println("getAllEmployeeByName4: " + sql);
        pStatement.setString(1, "%" + name + "%");
        resultSet = pStatement.executeQuery();
        return resultSet;
    }
}
